<template>

  <SearchInput v-if="!isSearch||search===''"
               focus
               v-model:value="search"
               @handleSearch="handleSearch"
               @clearSearch="clearSearch"></SearchInput>
  <view v-if="!isSearch||search===''">
    <SearchHot :hot-list="hotList" @clickHot="clickHot"></SearchHot>
    <SearchHistory :history-list="historyList"
                   @clearHistory="clearHistory"
                   @clickHistory="clickHistory"></SearchHistory>
  </view>
  <view v-show="isSearch&&search!==''">
    <SearchResult ref="resultRef">
      <template #header>
        <SearchInput
            v-if="isSearch&&search!==''"
            v-model:value="search"
            @handleSearch="handleSearch"
            @clearSearch="clearSearch"></SearchInput>
      </template>
    </SearchResult>
  </view>
</template>

<script setup lang="ts">

import {ref} from "vue";
import {onLoad, onReady} from "@dcloudio/uni-app";
import SearchHot from "@/pages/common/search/components/SearchHot.vue";
import SearchHistory from "@/pages/common/search/components/SearchHistory.vue";
import SearchResult from "@/pages/common/search/components/SearchResult.vue";
import SearchInput from "@/pages/common/search/components/SearchInput.vue";
import MrCustom from "@/components/common/MrCustom.vue";


const search = ref('')
const isSearch = ref(false)
const hotList = ref(['PICC', '免费','武汉','恩施'])
const historyList = ref([])
const resultRef = ref()


onLoad((option) => {

})

onReady(() => {
  historyList.value = JSON.parse(uni.getStorageSync('SearchHistory') || '[]')
})

const handleSearch = () => {
  isSearch.value = true
  let data = search.value.replace(/(^\s*)|(\s*$)/g, "")
  if (data.trim() != '') {
    historyList.value.forEach((key, index) => {
      if (key === data) {
        historyList.value.splice(index, 1)
      }
    })
    historyList.value.unshift(data)
    historyList.value = historyList.value.slice(0, 15)
    uni.setStorageSync('SearchHistory', JSON.stringify(historyList.value))
    resultRef.value.doSearch(3, search.value)
  } else {
    uni.showToast({
      title: '不能为空',
      icon: 'error'
    })
  }
}
const clickHistory = (value: any) => {
  search.value = value
  handleSearch()
}
const clearHistory = () => {
  historyList.value = []
  uni.removeStorageSync('SearchHistory')
}
const clickHot = (value: any) => {
  search.value = value
  handleSearch()
}
const clearSearch = () => {
  search.value = ''
  isSearch.value = false
}


</script>

<style scoped>

</style>